//
//  VMDataSource.m
//  DebugDemo
//
//  Created by XFB on 2018/11/16.
//  Copyright © 2018年 ZhouCheng. All rights reserved.
//

#import "VMDataSource.h"


@interface VMDataSource ()

@property (nonatomic, strong) IBInspectable NSString *cellIdentifier;
@property (nonatomic, copy) CellConfigureBeforeBlock cellConfigureBeforeBlock;
@property (nonatomic, copy) SelectCellBlock selectBlock;
@property (nonatomic, copy) ReloadDataBlcok reloadDataBlock;

@end

@implementation VMDataSource

- (instancetype)initWithIdentifier:(NSString *)identifier
                    configureBlock:(CellConfigureBeforeBlock)beforeBlock
                       selectBlock:(SelectCellBlock)selectBlock
                   reloadDataBlock:(ReloadDataBlcok)reloadDataBlock
{
    self = [super init];
    if (self) {
        _cellIdentifier = identifier;
        _cellConfigureBeforeBlock = beforeBlock;
        _selectBlock = selectBlock;
        _reloadDataBlock = reloadDataBlock;
    }
    return self;
}


- (void)addDataArray:(NSArray *)objects
{
    if (!objects) return;
    
    if (self.dataArray.count > 0) {
        [self.dataArray removeAllObjects];
    }
    
    [self.dataArray addObjectsFromArray:objects];
}

#pragma mark --- <UITableViewDataSource>
- (instancetype)modelsAtIndexPath:(NSIndexPath *)indexPath
{
    return self.dataArray.count > indexPath.row ? self.dataArray[indexPath.row] : nil;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count ? self.dataArray.count : 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:self.cellIdentifier forIndexPath:indexPath];
    id model = [self modelsAtIndexPath:indexPath];
    if (self.cellConfigureBeforeBlock) {
        self.cellConfigureBeforeBlock(cell, model, indexPath);
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    /// 点击事件通过block的方式传递出去
    self.selectBlock(indexPath);
}

- (NSMutableArray *)dataArray
{
    if (_dataArray == nil) {
        _dataArray = @[].mutableCopy;
    }
    return _dataArray;
}


@end
